package com.wbao.dianniu.tabstrip.fragments;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.powerfulrecyclerview.listener.OnRefreshListener;
import com.powerfulrecyclerview.ptr.HistoryThemeHeaderView;
import com.powerfulrecyclerview.ptr.PowerfulRecyclerView;
import com.powerfulrecyclerview.ptr.SimDividerItemDecoration;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.AmAddHeadAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.CarouselNotifyData;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.QuestV1Data;
import com.wbao.dianniu.fragment.LazyLoadBaseFragment;
import com.wbao.dianniu.listener.ICarouselNotifyListener;
import com.wbao.dianniu.listener.IHeadImageListener;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.listener.IQuestListV1Listener;
import com.wbao.dianniu.listener.InnerItemClickListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.CarouselNotifyManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.manager.QuestListV1Manager;
import com.wbao.dianniu.ui.AdInfoActivity;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.update.AmDataChangeManager.IAmDataListener;
import com.wbao.dianniu.update.HeadImageManger;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 心情
 *
 * @author yejianjun
 */
public class AmFragment extends LazyLoadBaseFragment implements IQuestListV1Listener, IAmDataListener, ICarouselNotifyListener, IHeadImageListener
        , InnerItemClickListener, IQuestDelListener, OnRefreshListener, AmAddHeadAdapter.OnItemClickListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;


    private final int TYPE_ANONYMOUS = 2;
    PowerfulRecyclerView recyclerView;

    //是否是下拉刷新
    private boolean isPullDown = true;
    private AmAddHeadAdapter adapter;
    private QuestListV1Manager manager;
    private AmDataChangeManager amDataChangeManager;
    private TextView nofityTV;
    private CarouselNotifyManager notifyManager;
    private LinearLayout carouselNotigyll;
    private HeadImageManger headImageManger;
    private QuestDelManager questDelManager;
    private RecyclerView.LayoutManager mLayoutManager;
    private HistoryThemeHeaderView header;
    // 是否上拉加载更多
    private int lastVisibleItem = 0;


    public static AmFragment instance() {
        AmFragment view = new AmFragment();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new AmAddHeadAdapter(getActivity(), 2);
        adapter.setItemClickListener(this);
        adapter.changeMoreStatus(AmAddHeadAdapter.PULLUP_LOAD_MORE);
    }

    /*@Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_fist_pager_anonymous, null);
        initManager();
        init(view);
        initWattingView(view);
        initLoadMoreListener();
        requestData();
        reqCarouselNotify();
        return view;
    }*/

    private void initManager() {
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        amDataChangeManager = AmDataChangeManager.getInstance();
        amDataChangeManager.addAmChangeListener(this);
        notifyManager = new CarouselNotifyManager(getContext());
        notifyManager.addCarouselNotifyListener(this);
        headImageManger = HeadImageManger.getInstance();
        headImageManger.addListener(this);
        questDelManager = new QuestDelManager(getContext());
        questDelManager.addQuestDelListener(this);
        manager = new QuestListV1Manager(getActivity());
        manager.addQuestListV1Listener(this);
    }

    private void initRecycler(View view) {
        recyclerView = view.findViewById(R.id.anonmous_listview);
        recyclerView.setAdapter(adapter);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        // 设置分割线
//        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        recyclerView.addItemDecoration(new SimDividerItemDecoration(getActivity()));

        // 设置adapter
        header = (HistoryThemeHeaderView) LayoutInflater.from(getContext()).inflate(R.layout.history_header_theme, recyclerView, false);
        recyclerView.setHeaderView(header);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshing(true);
        recyclerView.setOnRefreshListener(this);

    }

    private void init(View view) {
        carouselNotigyll = view.findViewById(R.id.carousel_notify_layout);
        nofityTV = view.findViewById(R.id.notify_tv);
        nofityTV.setSelected(true);

        initRecycler(view);
    }

    private void initWattingView(View view) {
        waittingLayout = view.findViewById(R.id.waitting_layout);
        waittingProBar = view.findViewById(R.id.waitting_progress);
        waittingTV = view.findViewById(R.id.waitting_text_desc);
    }


    /**
     * 上拉加载更多
     */
    private void initLoadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    //设置正在加载更多
                    adapter.changeMoreStatus(AmAddHeadAdapter.LOADING_MORE);
                    //请求下一页数据
                    isPullDown = false;
                    reqData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void requestData() {
        reqData();
    }

    /**
     * 轮播通知请求
     */
    private void reqCarouselNotify() {
        notifyManager.carouselNotify();
    }

    private void reqData() {
        if (isPullDown) {
            manager.questList(TYPE_ANONYMOUS, adapter.getFirstUpdateDate(), "down");
        } else {
            manager.questList(TYPE_ANONYMOUS, adapter.getLastUpdateDate(), "up");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeQuestListV1Listener(this);
        }
        if (null != amDataChangeManager)
            amDataChangeManager.removeAmChangeListener(this);
        if (null != headImageManger)
            headImageManger.removeListener(this);
        if (null != questDelManager)
            questDelManager.removeQuestDelListener(this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("AmFragment"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("AmFragment");
    }

    @Override
    public void addOneData(QaResponse addData) {
        // TODO Auto-generated method stub
        final int position = adapter.addOneQuestData(addData);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // 定位到最上面一条数据，位置发生偏移，需要加上两个addHeadview的内容
                recyclerView.setSelection(position);
            }
        });
    }

    @Override
    public void removeOneData(int questId) {
        // TODO Auto-generated method stub
        adapter.removeOneData(questId);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void priseNotify(int questId, int isGood, int goodCounts) {
        // TODO Auto-generated method stub
        adapter.priseNotify(questId, isGood, goodCounts);
    }

    @Override
    public void replyNotify(int questId, int answerCounts) {
        // TODO Auto-generated method stub
        adapter.replyNotify(questId, answerCounts);
    }

    @Override
    public void updateVisitor(int questId, int visitorCounts) {
        adapter.updateVisitor(questId, visitorCounts);
    }

    @Override
    public void onCarouseNotifyFailure(int errorCode, String errorMsg) {
        carouselNotigyll.setVisibility(View.GONE);
    }

    @Override
    public void onCarouseNotifySuccess(List<CarouselNotifyData> list) {
        if (null != list && list.size() > 0) {
            String content = "";
            for (CarouselNotifyData notifyData : list) {
                content += notifyData.getContent() + " ";
            }
            nofityTV.setText(content);
        } else {
            carouselNotigyll.setVisibility(View.GONE);
        }
    }

    @Override
    public void imageChange(String headCachePath) {

    }

    @Override
    public void dataChanged(String nickName, String headPic, String sex, String signate, String label) {
        Integer sexFlag = null;
        if (sex.equals("男")) {
            sexFlag = 1;
        } else if (sex.equals("女")) {
            sexFlag = 0;
        }
        adapter.updateHeadInfo(GlobalContext.getAccountId(), nickName, headPic, sexFlag, label);
    }

    @Override
    public void partnerNotify(int partner) {
        adapter.updatePartner(GlobalContext.getAccountId(), partner);
    }

    @Override
    public void itemClick(View v) {
        final int position;
        QaResponse resp;
        switch (v.getId()) {
            case R.id.am_adapter_layout:
                position = (Integer) v.getTag(R.id.am_adapter_layout);
                ActivityUtils.intoAmDetailActivity(getActivity(), adapter.getList().get(position).id);
                break;
            case R.id.am_pic_layout:
                position = (Integer) v.getTag(R.id.am_pic_layout);
                ActivityUtils.intoAmDetailActivity(getActivity(), adapter.getList().get(position).id);
                break;
            case R.id.anomyous_ad_pic_iv:
                position = (Integer) v.getTag(R.id.anomyous_ad_pic_iv);
                intentToAdACtivity(adapter.getList().get(position).advertToPageUrl);
                break;
            case R.id.ad_content_spanTV:
                position = (Integer) v.getTag(R.id.ad_content_spanTV);
                intentToAdACtivity(adapter.getList().get(position).advertToPageUrl);
                break;
            case R.id.include_answer_tv:
                position = (Integer) v.getTag(R.id.include_answer_tv);
                resp = adapter.getList().get(position);
                ActivityUtils.intoAmDetailActivity(getContext(), resp.id);
                break;
            case R.id.anonymous_content:
                position = (Integer) v.getTag(R.id.anonymous_content);
                resp = adapter.getList().get(position);
                if (resp.advert != 1) {
                    ActivityUtils.intoAmDetailActivity(getContext(), resp.id);
                }
                break;
            case R.id.user_name:
                position = (Integer) v.getTag(R.id.user_name);
                resp = adapter.getList().get(position);
                if (null != resp.anonymous && 0 == resp.anonymous) {
                    ActivityUtils.intoHeadInfoActivity(resp.userInfo.accountId, getContext());
                }
                break;
            case R.id.user_head:
                position = (Integer) v.getTag(R.id.user_head);
                resp = adapter.getList().get(position);
                if (null != resp.anonymous && 0 == resp.anonymous) {
                    ActivityUtils.intoHeadInfoActivity(resp.userInfo.accountId, getContext());
                }
                break;
            case R.id.include_forward_tv:
                String imageUrl = null;
                position = (Integer) v.getTag(R.id.include_forward_tv);
                resp = adapter.getList().get(position);
                if (TextUtils.isEmpty(resp.questImgs)) {
                    imageUrl = GlobalContext.cdndownUrl + "logo.png";
                } else {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                    imageUrl = imageUrls.get(0);
                }
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(getContext(), resp.content, 7, imageUrl, resp.id);
                break;
            case R.id.include_praise_tv:
                position = (Integer) v.getTag(R.id.include_praise_tv);
                resp = adapter.getList().get(position);
                if (resp.isGood == 0) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                if (null == amDataChangeManager) {
                    amDataChangeManager = AmDataChangeManager.getInstance();
                }
                amDataChangeManager.priseNotify(resp.id, resp.isGood, resp.goodCount);
                goodclick(resp.id);
                break;
            case R.id.include_delete_tv:
                // 删除传入的参数是Id
                position = (Integer) v.getTag(R.id.include_delete_tv);
                CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
                builder.setTitle("确认删除该条心情吗？");
                builder.setPositiveButton(getContext().getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (null != questDelManager) {
                                    questDelManager.deleteQuest(GlobalContext.getAccountId(), position);
                                    if (null == amDataChangeManager) {
                                        amDataChangeManager = AmDataChangeManager.getInstance();
                                    }
                                    amDataChangeManager.notifyRemove(position);
                                }
                            }
                        });
                builder.setNegativeButton(getContext().getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.set_top_content_tv:
                position = (Integer) v.getTag(R.id.set_top_content_tv);
                ActivityUtils.intoAmDetailActivity(getActivity(), adapter.getList().get(position).id);
                break;
            default:
                break;
        }

    }

    @Override
    public void onItemLongClick(View view, int position) {

    }

    private void goodclick(int questId) {
        QuestGoodManager manager = new QuestGoodManager(getContext());
        manager.good(GlobalContext.getAccountId(), questId);
    }

    private void intentToAdACtivity(String url) {
        Intent intent = new Intent();
        intent.putExtra(Const.BUNDLE_DATA, url);
        intent.setClass(getContext(), AdInfoActivity.class);
        startActivity(intent);
    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDelSuccess() {

    }

    @Override
    public void onRefresh() {
        //请求最新的数据
        isPullDown = true;
        reqData();
    }

    @Override
    public void onQuestListV1Failure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.GONE);
        adapter.changeMoreStatus(AmAddHeadAdapter.NO_LOAD_MORE);
        recyclerView.stopRefresh();
    }

    @Override
    public void onQuestListV1Success(QuestV1Data questV1Data) {
        waittingLayout.setVisibility(View.GONE);
        recyclerView.stopRefresh();
        if (null != questV1Data.questList) {
            if (isPullDown) {
                adapter.addForwardList(questV1Data.questList, questV1Data.topList);
                adapter.updateTopList(questV1Data.topList);
            } else {
                adapter.addBackwardList(questV1Data.questList);
            }
        }
        adapter.changeMoreStatus(AmAddHeadAdapter.NO_LOAD_MORE);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_fist_pager_anonymous;
    }

    @Override
    protected void initView(View view) {
        initManager();
        init(view);
        initWattingView(view);
        initLoadMoreListener();
    }

    @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        requestData();
        reqCarouselNotify();
    }

}
